package com.diana.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * Created by anzhi on 2019/3/17.
 */
@Component
public class JedisUtils {

    private static Logger log = LoggerFactory.getLogger(JedisUtils.class);

    private static String host;
    private static String password;
    private static int port;
    private static int timeout;
    private static int maxActive;
    private static int maxIdle;
    private static int maxWaitMillis;

    private static JedisPool jedisPool = null;

    /**
     * 获取jedis对象
     * @return
     */
    public static Jedis getJedis(){
        if(jedisPool==null){
            try {
                JedisPoolConfig config = new JedisPoolConfig();
                config.setMaxIdle(maxIdle);
                config.setMaxTotal(maxActive);
                config.setMaxWaitMillis(maxWaitMillis);
                jedisPool = new JedisPool(config, host, port, timeout, password);
                log.info("初始化JedisPool成功!地址:" + host + ":" + port);
            }catch (Exception e){
                log.info("初始化JedisPool异常:{}",e);
                return null;
            }
        }
        return jedisPool.getResource();
    }

    /**
     * 归回jedis对象
     * @param jedis
     */
    public static void returnJedis(Jedis jedis){
        if(jedis!=null){
            try {
                jedis.close();
            }catch (Exception e){
                jedis = null;
                log.error("Could not return the resource to the pool");
            }
        }
    }


    @Value("${spring.redis.host}")
    public void setHost(String host) {
        JedisUtils.host = host;
    }

    @Value("${spring.redis.port}")
    public void setPort(int port) {
        JedisUtils.port = port;
    }

    @Value("${spring.redis.timeout}")
    public void setTimeout(int timeout) {
        JedisUtils.timeout = timeout;
    }

    @Value("${spring.redis.password}")
    public void setPassword(String password) {
        JedisUtils.password = password;
    }

    @Value("${spring.redis.jedis.pool.max-active}")
    public void setMaxActive(int maxActive) {
        JedisUtils.maxActive = maxActive;
    }

    @Value("${spring.redis.jedis.pool.max-idle}")
    public void setMaxIdle(int maxIdle) {
        JedisUtils.maxIdle = maxIdle;
    }

    @Value("${spring.redis.jedis.pool.max-wait}")
    public void setmaxWaitMillis(int maxWaitMillis) {
        JedisUtils.maxWaitMillis = maxWaitMillis;
    }
}
